package com.liang.blog.controller;

import com.liang.blog.enmus.ResultCodeEnum;
import com.liang.blog.model.Result;
import com.liang.blog.model.UserInfo;
import com.liang.blog.service.UserService;
import com.liang.blog.utils.JwtUtils;
import com.liang.blog.utils.SecurityUtils;
import io.jsonwebtoken.lang.Assert;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userservice;

    @RequestMapping("/login")
    public Result login(String userName, String password) throws UnsupportedEncodingException {
       log.info("用户登录，userName：{}", userName);
        Assert.hasLength(userName,"用户名不能为空");
        Assert.hasLength(password,"密码不能为空");
        if (!StringUtils.hasLength(userName) && !StringUtils.hasLength(password)) {
           log.error("密码验证失败");
            return Result.fail(ResultCodeEnum.PARAM_INVAILD.getCode(), "账号或密码错误");
        }
        UserInfo userInfo = userservice.selectUserByName(userName);
        if (userInfo == null || userInfo.getId() == null) {
            return Result.fail(ResultCodeEnum.PARAM_INVAILD.getCode(), "用户不存在");
        }
        if (!SecurityUtils.verity(password,userInfo.getPassword())) {
            return Result.fail(ResultCodeEnum.PARAM_INVAILD.getCode(), "密码错误");
        }
        //密码正确的逻辑
        Map<String, Object> cliams = new HashMap<>();
        cliams.put("id", userInfo.getId());
        cliams.put("name", userInfo.getUserName());

        String jwt = JwtUtils.genJwt(cliams);
        return Result.success(jwt);
    }

    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request) {
        String userToken = request.getHeader("user_token_header");
        Integer userId = JwtUtils.getUserIdFromToken(userToken);
        Assert.notNull(userId,"用户未登录");
        UserInfo userInfo = userservice.selectUserInfoById(userId);
        return userInfo;
    }

    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId) {
       //1.根据博客id,获取作者Id
        //2.根据作者ID,获取作者信息
        Assert.notNull(blogId,"博客ID不能为null");
        return userservice.selectAuthorInfoByBlogId(blogId);
    }
}
